package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;

    /**
     * 新增套餐
     * @param checkgroupIds
     * @param setmeal
     */
    @Override
    @Transactional
    public void add(List<Integer> checkgroupIds, Setmeal setmeal) {
        //将套餐数据添加到套餐表中
        setmealMapper.add(setmeal);
        //将套餐和检查组的关联关系插入到中间表
        checkgroupIds.forEach(checkgroupId ->{
            setmealMapper.addSetmealAndCheckGroup(setmeal.getId(),checkgroupId);
        });
    }

    /**
     * 根据套餐id删除套餐和关联的检查组数据
     * @param id
     */
    @Override
    @Transactional
    public void deleteById(Integer id) {
        setmealMapper.deleteBySetmealId(id);
        setmealMapper.deleteById(id);
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        List<CheckGroup> checkGroups = setmealMapper.findCheckGroupBySetmealId(id);
        setmeal.setCheckGroups(checkGroups);
       return setmeal;
    }

    /**
     * 编辑套餐
     * @param checkGroupIds
     * @param setmeal
     */
    @Override
    @Transactional
    public void update(List<Integer> checkGroupIds, Setmeal setmeal) {
        //更新套餐数据
        setmealMapper.update(setmeal);
        //删除原来套餐和检查组关联关系，添加新的关联关系
        Integer setmealId = setmeal.getId();
        setmealMapper.deleteBySetmealId(setmealId);
        checkGroupIds.forEach(checkGroupId ->{
            setmealMapper.addSetmealAndCheckGroup(setmealId,checkGroupId);
        });
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.pageQuery(queryPageBean);
        return new PageResult(page.getTotal(),page.getResult());
    }
}
